﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VideoCache.Server.BLL;
using VideoCache.Server.Model;

namespace VideoCache.Server.MVCWeb.Attributes
{
    public class ActionAuthorizeAttribute : AuthorizeAttribute
    {
        private AuthorizeType _Type;

        public ActionAuthorizeAttribute(AuthorizeType type)
            : base()
        {
            this._Type = type;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (this._Type == AuthorizeType.None)
            {
                base.OnAuthorization(filterContext);

                return;
            }

            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                try
                {
                    UserInfo info = UserBLL.GetUserByName(filterContext.HttpContext.User.Identity.Name);
                    if (info == null)
                    {
                        this.RedirectToLogin(filterContext);
                    }

                    if (!RoleBLL.IsUserInRole(info.Id, (int)this._Type))
                    {
                        this.RedirectToLogin(filterContext);
                    }
                }
                catch (Exception ex)
                {
                    this.RedirectToLogin(filterContext);
                }
            }
            else
            {
                this.RedirectToLogin(filterContext);
            }
        }

        private void RedirectToLogin(AuthorizationContext filterContext)
        {
            if (this._Type == AuthorizeType.Administrator)
            {
                filterContext.HttpContext.Response.Redirect("~/admin/login");
            }
            else
            {
                filterContext.HttpContext.Response.Redirect("~/member/login?returnUrl=" + HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.ToString()));
            }
        }
    }

    public enum AuthorizeType : int
    {
        None = 0,
        Administrator = 1,
        Member = 2,
        Netbar = 3,
        Agent = 4
    }
}